package com.ruiysoft.service.cart.impl;


import com.ruiysoft.service.cart.ICartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements ICartService {
	private Logger logger  = LoggerFactory.getLogger(getClass());

	@Resource
	private RedisTemplate<String,Long> template;
	private static final String CART_SHOP_USER_KEY="CART:";
	@Override
	public void addSkuIdNum(Long shopId, Long userId, Long skuId, Integer num) {
		if(num!=null&&num>0){
			String key = getKey(shopId,userId);
			Long[] skuIdArr = new Long[num];
			for (int i = 0; i < skuIdArr.length; i++) {
				skuIdArr[i] = skuId;
			}
			template.opsForList().leftPushAll(key,skuIdArr);
		}
	}

	@Override
	public void delSkuId(Long shopId, Long userId, Long skuId) {
		subtractSkuIdNum(shopId,userId,skuId,0);
	}

	@Override
	public void subtractSkuIdNum(Long shopId, Long userId, Long skuId, Integer num) {
		String key = getKey(shopId,userId);
		//负数从后边开始删除
		template.opsForList().remove(key,-num.longValue(),skuId);

	}

	@Override
	public Integer cartSum(Long shopId, Long userId) {
		String key = getKey(shopId,userId);
		return template.opsForList().size(key).intValue();
	}

	@Override
	public LinkedHashMap<Long, Long> cartList(Long shopId, Long userId) {
		String key = getKey(shopId,userId);
			List<Long> skuIdList = template.opsForList().range(key,0,-1);

		return template.opsForList().range(key,0,-1).stream()
				.collect(Collectors.groupingBy(a-> a,LinkedHashMap::new,Collectors.counting()));
	}

	@Override
	public void delSkuIds(Long shopId, Long userId, List<Long> skuIds) {
		if(skuIds!=null&&!skuIds.isEmpty()){
			skuIds.forEach(skuId -> subtractSkuIdNum(shopId,userId,skuId,0));
		}
	}

	private String getKey(Long shopId, Long userId) {
		return CART_SHOP_USER_KEY+shopId+":"+userId;
	}
}
